#include "logprintf.h"
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef __ANDROID__
#include <android/log.h>
#endif

int g_nLogLevel = X_LOG_ASSERT;
int g_nLogType = X_LOG_TYPE_CONSOLE;
char g_LogFileName[512] = {0x0};

#ifndef NULL
#define NULL (void*)0
#endif

void XConfigLog(int nLevel, int nType, char* fileName)
{
	g_nLogLevel = nLevel;
	g_nLogType = nType;
	if (NULL != fileName && strlen(fileName) > 0)
	{
		strcpy(g_LogFileName, fileName);
	}
}

void XLogPrintf(int nLevel, const char* tag, const char* fmt, ...)
{
	if (g_nLogLevel <= nLevel)
	{
		if (g_nLogType == X_LOG_TYPE_CONSOLE)
		{
#ifdef __ANDROID__
			va_list arg;
			va_start(arg, fmt);
			__android_log_vprint(nLevel, tag, fmt, arg);
			va_end(arg);
#else
			va_list arg;
			va_start(arg, fmt);
			printf("TAG[%s],", tag);
			printf(fmt, arg);
			va_end(arg);
#endif
		}
		else if (g_nLogType == X_LOG_TYPE_FILE)
		{
			if (strlen(g_LogFileName) > 0)
			{
				FILE* pFile = fopen(g_LogFileName, "a+");
				if (NULL != pFile)
				{
					va_list arg;
					va_start(arg, fmt);
					fprintf(pFile, "TAG[%s],", tag);
					fprintf(pFile, fmt, arg);
					va_end(arg);
					fclose(pFile);
				}
			}
		}
#ifdef _WIN32
		else if (g_nLogType == X_LOG_TYPE_DBGVIEW)
		{
			char szBuffer[8192]={0};
			int nPos = 0;
			va_list arg;
			va_start(arg,fmt);
			if (NULL == tag)
			{
				nPos = _snprintf(szBuffer+nPos, sizeof(szBuffer)-1-nPos, "TAG[%s],", LOG_TAG);
			}
			else
			{
				nPos = _snprintf(szBuffer+nPos, sizeof(szBuffer)-1-nPos, "TAG[%s],", tag);
			}
			_vsnprintf(szBuffer + nPos, sizeof(szBuffer)-1 - nPos, fmt, arg);
			va_end(arg);
			OutputDebugStringA(szBuffer);
		}
#endif
	}
}
